package library.net.retrofit.interceptor;

import java.io.IOException;

import library.net.RxRetrofitUtils;
import library.common.util.NetworkUtil;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Cache-Time: user-defined cache max time
 *
 * @author Created by qiang.hou on 2017/11/19.
 * @version 1.0
 */
public class RxNetCacheInterceptor implements Interceptor {

    public RxNetCacheInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (!NetworkUtil.isNetworkAvailable(RxRetrofitUtils.getInstance().getApplication())) {
            /* new request */
            Request.Builder requestBuilder = request.newBuilder()
                    .method(request.method(), request.body());
            /* force from cache when net work is unavailable */
            Request newRequest = requestBuilder
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            /* 6 hours available */
            int maxStale = 60 * 60 * 6;
            return chain.proceed(newRequest).newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
        // 有网络的时候不做处理
        return chain.proceed(request);
    }
}
